package cn.xspace.wnx.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.AuthorityController;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.adapter.SearchResultAdaper;
import cn.xspace.wnx.db.OrgAllUserDao;
import cn.xspace.library.bean.OrgDeptUserBean;
import cn.xspace.wnx.util.ForwardHelper;
import cn.xspace.wnx.util.Navigator;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/10/27.
 */
public class UserSearchResultActivity extends BaseActivity {
    private static final String TAG = "UserSearchResultActivit";
    private TextView searchEdit;
    private TextView cancelText;
    private LinearLayout topLinear;
    private LayoutInflater layoutInflater;
    private String searchKey = "";
    private String searchType = "";
    private Map<String, Object> requestMap;
    private String userId = "";
    private String deptId = "";
    private List<OrgDeptUserBean> serviceObjList;
    private List<OrgDeptUserBean> orgUserList;
    private View resultOrgView;
    private SearchResultAdaper resultAdapter;
    private ListView orgListview;
    private View headerView;
    private ArrayList<OrgDeptUserBean> dataList;
    private String operate = "";

    private boolean isBishanSpecial;
    private String isBelonePost = "0";
    private String isDirectauth = "0";
    private MsgRecordEntity recordEntity;
    private String groupId;
    private int groupType;
    private String groupMemberSearchUrl = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected void getIntentData() {
        super.getIntentData();
        try {
            Bundle bundle = getIntent().getBundleExtra(BldNavigation.KEY_BUNDLER);
            if (bundle != null) {
                searchType = bundle.getString(BldNavigation.SEARCH_TYPE); //获取搜索类型
                if (TextUtils.equals(BldNavigation.SEARCH_GROUP_MEMBER, searchType)) { //查询群组内成员
                    operate = bundle.getString(EventBusConstant.ACTION_KEY);
                    groupId = bundle.getString(ChatInfoActivity.GROUP_ID);
                    groupType = bundle.getInt(ChatInfoActivity.GROUP_TYPE);
                } else if (TextUtils.equals(BldNavigation.SEARCH_MY_FRIEND, searchType)) { //查询好友
                    dataList = (ArrayList<OrgDeptUserBean>) bundle.getSerializable(MyFriendActivity.SELECTED_MEMBERS);
                }
                recordEntity = (MsgRecordEntity) bundle.getSerializable(MsgForwardActivity.FORWARD_ENTITY);
                LogUtil.d("searchType>>" + searchType);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_user_search);
    }

    @Override
    protected void initFindViewById() {
        super.initFindViewById();
        searchEdit = (TextView) findViewById(R.id.edit_search);
        cancelText = (TextView) findViewById(R.id.txt_cancel);
        topLinear = (LinearLayout) findViewById(R.id.linear_top);
        layoutInflater = LayoutInflater.from(mContext);
        resultOrgView = layoutInflater.inflate(R.layout.layout_result_search_item, null);
        orgListview = (ListView) resultOrgView.findViewById(R.id.listview_item);
        if (!isSearchGroupMember()) { //如果不是查询群组内容成员
            //存在同事
            headerView = layoutInflater.inflate(R.layout.header_result_search, null);
            TextView textView = (TextView) headerView.findViewById(R.id.txt_header);
            if (isSearchMyFriend()) {
                textView.setText(R.string.friend);
            }
            orgListview.addHeaderView(headerView);
        }

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 20, 0, 0);
        resultOrgView.setLayoutParams(params);
    }

    /**
     * 是否是查询群组成员内成员
     *
     * @return
     */
    private boolean isSearchGroupMember() {
        return !TextUtils.isEmpty(searchType) && TextUtils.equals(searchType, BldNavigation.SEARCH_GROUP_MEMBER);
    }

    /**
     * 是否是查询好友成员
     *
     * @return
     */
    private boolean isSearchMyFriend() {
        return !TextUtils.isEmpty(searchType) && TextUtils.equals(searchType, BldNavigation.SEARCH_MY_FRIEND);
    }

    @Override
    protected void initData() {
        orgUserList = new ArrayList<>();
        serviceObjList = new ArrayList<>();
        resultAdapter = new SearchResultAdaper(mContext, orgUserList);
        orgListview.setAdapter(resultAdapter);
        userId = MyInfoUtil.getMyUserid(mContext);
        deptId = MyInfoUtil.getUseOrgId(mContext);
        if (AuthorityController.getInstance().iSBiShanAppOrgAndDirect()) {
            isBishanSpecial = true;
            //璧山特殊权限，app机构id
            deptId = MyInfoUtil.getAppOrgId();
            LogUtil.d("MyInfoUtil.getAppOrgId>>" + deptId);
        }
        //直属
        if (isBishanSpecial || AuthorityController.getInstance().isCanViewAddressbookDirectDept()) {
            isDirectauth = "1";
        }
        //归口
        if ((AuthorityController.getInstance().iSBiShanAppOrgAndDirect())) {
            isBelonePost = "1";
        } else {
            if (AuthorityController.getInstance().isBelong()) {
                isBelonePost = "1";
            }
        }
        requestMap = new HashMap<>();
        if (isSearchGroupMember()) { //群组内搜索
            requestMap.put(RequestConstant.KEY_USER_ID, userId);
            requestMap.put(RequestConstant.KEY_GROUP_ID, groupId);
            groupMemberSearchUrl = Constants.QUERY_GROUP_MEMBERS;
            if (groupType == Type.GroupType.PROFESSIONAL) {
                groupMemberSearchUrl = Constants.QUERY_PRO_GROUP_MEMBERS;
            }
        } else { //普通搜索
            requestMap.put(RequestConstant.KEY_USER_ID, userId);
            requestMap.put(RequestConstant.KEY_ORG_ID, deptId);
            requestMap.put(RequestConstant.HAS_DIRECTAUTH, isDirectauth);
            requestMap.put(RequestConstant.HAS_BELONGAUTH, isBelonePost);
            requestMap.put(RequestConstant.HAS_PARTIMEAUTH, "1");
//            requestResult();
//            showWaitDialog();
        }

        showSoftInputMethod();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                topLinear.removeView(resultOrgView);
                LogUtil.d(s.toString());
                searchKey = s.toString();
//                requestResult();
                if (!TextUtils.isEmpty(searchKey)) {
                    if (isSearchGroupMember()) {
                        requestGroupMember();
                    } else if (isSearchMyFriend()) {
                        myFriendsSearch();
                    } else {
//                        requestDataLocal();
                        requestResult();
                    }

                }
            }
        });
        cancelText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        orgListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int headCount = orgListview.getHeaderViewsCount();
                LogUtil.d("headCount>" + headCount);
                if (position == headCount - 1) {
                    return;
                }

                final OrgDeptUserBean bean = orgUserList.get(position - headCount);
                if (recordEntity != null) { //转发
                    if (TextUtils.equals(userId, bean.user_id)) {
                        T.showShort(mContext, R.string.cant_forward_toself);
                        return;
                    }
                    ForwardHelper.getInstance().confirmBeforeForward(mContext, new ButtonClickListener() {
                        @Override
                        public void buttonClick(View view) {
                            LogUtil.d("确认");
                            ForwardHelper.getInstance().sendMessageRecordSingleChat(mContext, recordEntity, bean);
                            Map<String, Object> event = new HashMap<String, Object>();
                            event.put(EventBusConstant.TYPE, EventBusConstant.FINISH_PAGE_FORWARD);
                            EventBus.getDefault().post(event);
                            finish();
                        }
                    }, recordEntity, bean.user_name);
                } else {
                    if (ChatInfoActivity.GROUP_OWNER_TURN.equals(operate)) { //转让群组
                        LogUtil.d(bean.toString());
                        Map<String, Object> dataMap = new HashMap<>();
                        dataMap.put(EventBusConstant.TYPE, ChatInfoActivity.TAG);
                        dataMap.put(EventBusConstant.ACTION_KEY, ChatInfoActivity.GROUP_OWNER_TURN);
                        dataMap.put(EventBusConstant.ACTION_VALUE, bean);
                        EventBus.getDefault().post(dataMap);
                        Map<String, Object> finishMap = new HashMap<String, Object>();
                        finishMap.put(EventBusConstant.TYPE, GroupMembersListActivity.TAG);
                        finishMap.put(EventBusConstant.ACTION_KEY, GroupMembersListActivity.FINISH);
                        EventBus.getDefault().post(finishMap);
                        finish();
                    } else {
                        Navigator.startPersonCardActivity(mContext, orgUserList.get(position - headCount).user_id);
                    }
                }

            }
        });
    }

    /**
     * 搜索群组内成员
     */
    private void requestGroupMember() {
        requestMap.put(RequestConstant.KEY_USER_NAME, searchKey);
        registerSubscription(OkHttpManager.getInstance().commonRequest(groupMemberSearchUrl, requestMap)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<OrgDeptUserBean>>() {
                    @Override
                    public List<OrgDeptUserBean> call(BaseReturnBean baseReturnBean) {
                        List<OrgDeptUserBean> dataList = new ArrayList<>();
                        Gson mGson = new Gson();
                        dataList = mGson.fromJson(baseReturnBean.data, new
                                TypeToken<List<OrgDeptUserBean>>() {
                                }.getType());
                        return dataList;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OrgDeptUserBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<OrgDeptUserBean> dataList) {
                        orgUserList.clear();
                        LogUtil.d(TAG, "dataListSize>>>>>" + dataList.size());
//                        hideWaitDialog();
                        if (dataList.size() > 0) {
                            orgUserList.addAll(dataList);
                            topLinear.addView(resultOrgView);
                            resultAdapter.notifyDataSetChanged();
                        }
                    }
                }));
    }

    /**
     * 搜索好友列表的内容
     */
    private void myFriendsSearch() {
        orgUserList.clear();
        for (OrgDeptUserBean bean : dataList) {
            if (bean.user_name.contains(searchKey)) {
                orgUserList.add(bean);
            }
        }

        if (orgUserList.size() > 0) {
            topLinear.addView(resultOrgView);
            resultAdapter.notifyDataSetChanged();
        }
    }

    private void requestResult() {
        requestMap.put(RequestConstant.SEARCH_NAME, searchKey);
        registerSubscription(OkHttpManager.getInstance().commonRequest(Constants.SEARCH_CONTACT_USER, requestMap)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<OrgDeptUserBean>>() {
                    @Override
                    public List<OrgDeptUserBean> call(BaseReturnBean baseReturnBean) {
                        List<OrgDeptUserBean> dataList = new ArrayList<>();
                        try {
                            JSONObject dataJson = new JSONObject(baseReturnBean.data);
                            Gson mGson = new Gson();
                            serviceObjList = mGson.fromJson(dataJson.optString("serObjList"), new
                                    TypeToken<List<OrgDeptUserBean>>() {
                                    }.getType());
                            dataList = mGson.fromJson(dataJson.optString("deptUserList"), new
                                    TypeToken<List<OrgDeptUserBean>>() {
                                    }.getType());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return dataList;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OrgDeptUserBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<OrgDeptUserBean> dataList) {
                        orgUserList.clear();
                        LogUtil.d(TAG, "dataListSize>>>>>" + dataList.size());
//                        hideWaitDialog();
                        if (dataList.size() > 0) {
                            orgUserList.addAll(dataList);
                            topLinear.addView(resultOrgView);
                            resultAdapter.notifyDataSetChanged();
                        }
                    }
                }));
    }

    private void requestDataLocal() {

        registerSubscription(OrgAllUserDao.getInstance().getOrgUserData().getOrgUserList()
                .subscribeOn(Schedulers.io())
                .map(new Func1<List<OrgDeptUserBean>, List<OrgDeptUserBean>>() {
                    @Override
                    public List<OrgDeptUserBean> call(List<OrgDeptUserBean> sourceList) {
                        List<OrgDeptUserBean> targetList = new ArrayList<OrgDeptUserBean>();
                        for (OrgDeptUserBean bean : sourceList) {
                            if (bean.user_name.contains(searchKey)) {
                                targetList.add(bean);
                                bean.org_name = MyInfoUtil.getDeptName();
                            }
                        }
                        return targetList;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OrgDeptUserBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<OrgDeptUserBean> dataList) {
                        orgUserList.clear();
                        LogUtil.d(TAG, "dataListSize>>>>>" + dataList.size());
                        if (dataList.size() > 0) {
                            orgUserList.addAll(dataList);

                            topLinear.addView(resultOrgView);
                            resultAdapter.notifyDataSetChanged();
                        }

                    }
                }));
        //获取本地数据
    }
}
